# This example formulates and solves the following simple bilinear model:
#  maximize    x
#  subject to  x + y + z <= 10
#              x * y <= 2         (bilinear inequality 双线性不等式)
#              x * z + y * z = 1  (bilinear equality  双线性等式)
#              x, y, z non-negative (x integral in second version)

import  gurobipy as gp
from gurobipy import *

m = gp.Model('billnear')

x = m.addVar( name="x")
y = m.addVar( name="y")
z = m.addVar( name="z")

m.setObjective( x , GRB.MAXIMIZE)

m.addConstr(x + y + z <= 10 ,'c0')
m.addConstr(x * y <= 2 ,'bilinear0')
m.addConstr(x * z + y * z == 1 ,'bilinear1')

try:
    m.optimize()    #调用失败-需要将非凸二次线性规划设置为2
except gp.GurobiError:   # 由于非凸性，优化失败
    print("Optimize failed due to non-convexity")

#  Solve bilinear model
m.params.NonConvex = 2
m.optimize()

m.printAttr('x')

#  约束x为整数，再解一次
x.vType = GRB.INTEGER
m.optimize()

m.printAttr('x')
